<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebRTC Demo Server</title>
    <script src="../../../Research/bg-web-rtcstudy/Web/js/peerjs.min.js"></script>
    <script type="application/javascript">
        /**
         * 这里先定义全局变量
         */
        let local_peer = null;    // 本地peer对象
        let local_peer_id = null;
        let last_local_peer_id = null;
        let remote_peer_conn = null;
        let stun_address = "";

        /**
         * 初始化函数
         */
        function onClickBtnInitialize() {
            stun_address = document.getElementById("stun_address").value;
            local_peer_id = document.getElementById("myid").value;

            let peer_config = {config: {'iceServers': [{ urls: [stun_address] }]}};

            // Create own peer object with connection to shared PeerJS server
            local_peer = new Peer(local_peer_id, peer_config);

            // 定义消息回调
            local_peer.on('open', function (id) {
                // Workaround for peer.reconnect deleting previous id
                if (local_peer.id === null) {
                    console.log('Received null id from peer open');
                    local_peer.id = last_local_peer_id;
                } else {
                    last_local_peer_id = local_peer.id;
                }

                console.log('Local ID: ' + local_peer.id);
            });
            local_peer.on('connection', function (c) {
                // Allow only a single connection
                if (remote_peer_conn && remote_peer_conn.open) {
                    c.on('open', function() {
                        c.send("Already connected to another client");
                        setTimeout(function() { c.close(); }, 500);
                    });
                    return;
                }

                remote_peer_conn = c;
                console.log("Connected to: " + remote_peer_conn.peer);
                ready();
            });
            local_peer.on('disconnected', function () {
                console.log('Connection lost. Please reconnect');

                // Workaround for peer.reconnect deleting previous id
                local_peer.id = last_local_peer_id;
                local_peer._lastServerId = last_local_peer_id;
                local_peer.reconnect();
            });
            local_peer.on('close', function() {
                remote_peer_conn = null;
                console.log('Connection destroyed');
            });
            local_peer.on('error', function (err) {
                console.log(err);
                alert('' + err);
            });
        }

        /**
         * 连接成功后，注册数据接受的回调函数
         */
        function ready() {
            remote_peer_conn.on('data', function (data) {
                console.log("Data recieved : " + data);
                updateMessageRecord(remote_peer_conn.id, data)
            });
            remote_peer_conn.on('close', function () {
                console.log("Connection reset. Awaiting connection...");
                remote_peer_conn = null;
            });
        }

        /**
         *
         */
        function onClickBtnSendMessage() {
            let message = document.getElementById("message_box").value;
            if (message == "") {
                return 0;
            } else {
                remote_peer_conn.send(message);
                updateMessageRecord(local_peer_id, message);
            }

        }

        /**
         *
         */
        function updateMessageRecord(peer_id, data) {
            let message_record = document.getElementById("message_record");
            let message_record_msg = message_record.innerText;
            if (message_record_msg == "") {
                message_record_msg += remote_peer_conn.id + "\r\n" + data;
            } else {
                message_record_msg += "\r\n\r\n" + remote_peer_conn.id + "\r\n" + data;
            }

            message_record.innerText = message_record_msg;
        }
    </script>
</head>
<body>
    <span>Click "Initialize" button to initialize peer.</span><input type="button" id="initialize" value="Initialize" onclick="onClickBtnInitialize()" /><br />
    <hr>
    <span>STUN Address:</span><label for="stun_address"></label><input type="text" id="stun_address" value="stun:stun.voipstunt.com" /><br />
    <span>TURN Address:</span><label for="turn_address"></label><input type="text" id="turn_address" value="" /><br />
    <span>My ID : </span><label for="myid"></label><input type="text" id="myid" value="100001" /><br />
    <input type="button" id="connect" value="Connect">
    <hr>
    <span>Message record</span><br />
    <textarea id="message_record" class="message_record" rows="20" cols="80">init</textarea><br />
    <span>Message : </span><input type="text" id="message_box" value="" /><input type="button" value="Send"  onclick="onClickBtnSendMessage()" />

</body>
</html>